#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sqlite3.h>




void create_table()
{
    //创建文件
    sqlite3*db=NULL;
    char *errmsg=NULL;
    if(sqlite3_open("user.db",&db)!=SQLITE_OK)
    {
        printf("open fail\n");
        return ;
    }

    //创建表格
    const char *sql = "CREATE TABLE IF NOT EXISTS user ("
                      "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                      "username TEXT NOT NULL UNIQUE,"
                      "passwd TEXT NOT NULL);";
    int ret=sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(ret!=SQLITE_OK)
    {
        printf("create fail\n");
        return ;
    }

    //注册用户
    char username[50],passwd[50];
    printf("请输入用户名\n");
    scanf("%s",username);
    printf("请输入密码\n");
    scanf("%s",passwd);
    char sql1[256]="";
    sprintf(sql1,"insert into user(username,passwd) values('%s','%s');",username,passwd);
    int ret1=sqlite3_exec(db,sql1,NULL,NULL,&errmsg);
    if (ret1!= SQLITE_OK)
    {
        // 如果错误是由于唯一约束冲突导致的（SQLITE_CONSTRAINT）
        if (sqlite3_errcode(db) == SQLITE_CONSTRAINT)
        {
            printf("用户名重名，请选择其他用户名！\n");
        }
        else
        {
            printf("插入数据失败: %s\n", errmsg);
        }
        sqlite3_free(errmsg);
    }

    else
    {
        printf("用户注册成功！\n");
    }

    sqlite3_close(db);
}

int main()
{
    create_table();

    return 0;
}